import sqlite3
import json
from typing import Dict, List
from tqdm import tqdm
from Evaluator import evaluate

datasets = 'datasets/data_full/'

book_dict = json.load(open(f'{datasets}/book_data/book_dict.json', 'rt'))
user_dict = json.load(open(f'{datasets}/user_data/user_dict.json', 'rt'))

result: Dict[int, List[int]] = {}

# Read from rec
conn = sqlite3.connect('DB_20211003_180339.db')
cursor = conn.execute('select * from book_info, book_rec, user_info where book_info.book_id == book_rec.book_id and book_rec.user_id == user_info.user_id')

# modify book_dict
new_book_dict = {}

for k, v in book_dict.items():
    a, b, c = k.split('@')
    c = c.split(' ')[0]
    new_book_dict[f'{b}@{c}'] = v

for row in tqdm(cursor):
    _, ISBN, code, title, _, _, _, sid = row
    book_key = f'{ISBN}@{code}'
    if sid not in user_dict:
        print(f'{sid} not in user_dict')
        continue
    if book_key not in new_book_dict:
        print(f'{book_key} not in book_dict')
        continue

    user_id = user_dict[sid]
    book_id = new_book_dict[book_key]

    if user_id not in result: result[user_id] = []
    result[user_id].append(book_id)

# Evaluate
evaluate(result, cold_start=True)
